<?php
namespace app\common\service;

use think\Db;
use think\Model;

class CouponService extends BaseService
{

    public function getCouponList($sid, $p, $pageSize)
    {
        $field = 'coupon_id,coupon_name,coupon_price,coupon_end,surplus,receive,use_num,status,coupon_type';
        $where = [
            'sid' => $sid,
            'status' => ['<>', -1]
        ];
        $count = db('coupon')->where($where)->count();
        $list = db('coupon')
            ->field($field)
            ->where($where)
            ->order('add_time DESC')
            ->limit(($p - 1) * $pageSize, $pageSize)
            ->select();
        if ($list) {
            foreach ($list as $k => $v) {
                $list[$k]['coupon_end'] = date('Y.m.d', $v['coupon_end']);
                if (time() > $v['coupon_end']) {
                    $list[$k]['status'] = 3; //已过期
                }
            }
        }
        $data = [
            'page' => [
                'count' => $count
            ],
            'content' => $list
        ];
        return $data;
    }


    /**
     * 后台: 新增优惠券
     * @param $sid
     * @param array $postParam
     * @return array
     */
    public function addCoupon($sid, $postParam = [])
    {
        //查询是否含有有效的相同名称、相同面额的优惠券
        $info = db('coupon')
            ->where([
                'sid' => $sid,
                'coupon_name' => $postParam['coupon_name'],
                'coupon_price' => $postParam['coupon_price'],
                'coupon_end' => ['>', time()]
            ])
            ->find();
        if ($info) {
            return ['status' => 0, 'msg' => '已存在相同信息的优惠券'];
        }
        $data = [
            'sid' => $sid,
            'coupon_name' => $postParam['coupon_name'],
            'coupon_price' => $postParam['coupon_price'],
            'sum' => $postParam['sum'],
            'surplus' => $postParam['sum'],
            'coupon_begin' => strtotime($postParam['coupon_begin']),
            'coupon_end' => strtotime($postParam['coupon_end']) + 86399,
            'receive_obj' => $postParam['receive_obj'] ? implode(',', $postParam['receive_obj']) : 0,
            'receive_classid' => $postParam['receive_classid'] ? implode(',', $postParam['receive_classid']) : 0,
            'coupon_type' => $postParam['receive_classid'] == 0 ? 1 : 2,
            'add_time' => time()
        ];
        $r = db('coupon')->insert($data);
        return $r === false ? ['status' => 0, 'msg' => '新增失败'] : ['status' => 1, 'msg' => '新增成功'];
    }


    /**
     * 后台: 发放或停止发放优惠券
     * @param $sid
     * @param $coupon_id
     * @param $status
     * @return array
     * @throws \think\Exception
     */
    public function changeCouponStatus($sid, $coupon_id, $status)
    {
        $where = [
            'sid' => $sid,
            'coupon_id' => $coupon_id,
            'status' => $status == 1 ? ['in', [0, 2]] : 1,
//            'coupon_end' => ['>', time()]
        ];
        $info = db('coupon')->where($where)->find();
        if (!$info) {
            return ['status' => 0, 'msg' => '未找到相关优惠券'];
        }
        $update = [
            'status' => $status == 1 ? 1 : 2,
            'edit_time' => time()
        ];
        $r = db('coupon')->where(['coupon_id' => $coupon_id])->update($update);
        return $r === false ? ['status' => 0, 'msg' => '修改失败'] : ['status' => 1, 'msg' => '修改成功'];
    }

    /**
     * 后台: 获取指定发放的用户列表
     * @param $sid
     * @param $coupon_id
     * @param $search
     * @param $p
     * @param $pageSize
     * @return array
     */
    public function getAppointUserList($sid, $coupon_id, $search, $p, $pageSize)
    {
        $where = [
            'sid' => $sid,
            'coupon_id' => $coupon_id,
            'status' => ['<>', -1],
            'coupon_end' => ['>', time()]
        ];
        $info = db('coupon')->where($where)->find();
        if (!$info) {
            return ['status' => 0, 'msg' => '未找到相关优惠券'];
        }

        $condition = [];
        $condition['ui.sid'] = $sid;
        $condition['ui.is_unsubscribe'] = 0;
        if ($search) {
            $condition['u.user_nickname|u.user_mobile|s.phone'] = $search;
        }

        //查询已经领取的用户ID
        $u_coupon = db('user_coupon')->field('uid')->where(['sid' => $sid, 'coupon_id' => $coupon_id])->select();
        if ($u_coupon) {
            $uids = [];
            foreach ($u_coupon as $key => $val) {
                $uids[$key] = $val['uid'];
            }
            $condition['ui.userid'] = ['not in', $uids];
        }


        $field = 'u.user_id as uid,u.user_nickname,u.user_mobile,s.phone';
        $count = db('user_integral ui')
            ->join('user u', 'ui.userid=u.user_id')
            ->join('students s', 'ui.userid=s.uid', 'LEFT')
            ->where($condition)
            ->count();
        $list = db('user_integral ui')
            ->join('user u', 'ui.userid=u.user_id')
            ->join('students s', 'ui.userid=s.uid', 'LEFT')
            ->field($field)
            ->where($condition)
            ->limit(($p - 1) * $pageSize, $pageSize)
            ->select();
        if ($list) {
            foreach ($list as $k => $v) {
                if ($v['phone']) {
                    $list[$k]['user_mobile'] = $v['phone'];
                }
                unset($list[$k]['phone']);
            }
        }
        $data = [
            'page' => [
                'count' => $count
            ],
            'content' => $list
        ];
        return $data;
    }

    /**
     * 后台: 指定发放给某用户
     * @param $sid
     * @param $uid
     * @param $coupon_id
     * @return array
     */
    public function appointSendToUser($sid, $uids = [], $coupon_id)
    {
        if (!$uids) {
            return ['status' => 0, 'msg' => '找不到相关用户'];
        }
        $where = [
            'sid' => $sid,
            'coupon_id' => $coupon_id,
            'status' => ['<>', -1],
            'coupon_end' => ['>', time()]
        ];
        $info = db('coupon')->where($where)->find();
        if (!$info) {
            return ['status' => 0, 'msg' => '未找到相关优惠券'];
        }

        //是否领取过
        $recieve = db('user_coupon')->where(['sid' => $sid, 'uid' => ['in', $uids], 'coupon_id' => $coupon_id])->find();
        if ($recieve) {
            return ['status' => 0, 'msg' => '存在用户已经领取过'];
        }

        $count = count($uids);

        //剩余数量
        $surplus = db('coupon')->where(['sid' => $sid, 'coupon_id' => $coupon_id])->value('surplus');
        if ($surplus < $count) {
            return ['status' => 0, 'msg' => '优惠券剩余数量不足'];
        }

        $data = [
            'sid' => $sid,
            'coupon_id' => $coupon_id,
            'add_time' => time(),
            'is_admin_appoint' => 1,
            'status' => 0
        ];

        $insert_data = [];
        foreach ($uids as $k => $v) {
            $data['uid'] = $v;
            $insert_data[$k] = $data;
        }

        Db::startTrans();
        try {
            db('user_coupon')->insertAll($insert_data);
            //减少优惠券发放数量
            db('coupon')->where(['coupon_id' => $coupon_id])->setDec('surplus', $count);
            //增加优惠券领取数量
            db('coupon')->where(['coupon_id' => $coupon_id])->setInc('receive', $count);
            Db::commit();
            return ['status' => 1, 'msg' => '发放成功'];
        } catch (\Exception $e) {
            Db::rollback();
            return ['status' => 0, 'msg' => '发放失败'];
        }
    }

    /**
     * 后台: 获取优惠券领取列表
     * @param $sid
     * @param $p
     * @param $pageSize
     * @return array
     */
    public function getCouponReceiveList($sid, $p, $pageSize)
    {
        $where = ['uc.sid' => $sid];
        $field = 'uc.id,uc.uid,uc.coupon_id,uc.status,uc.add_time,uc.use_time,uc.presenter_uid,c.coupon_name,c.coupon_price,u.user_nickname';
        $count = db('user_coupon uc')
            ->join('coupon c', 'uc.coupon_id=c.coupon_id')
            ->join('user u', 'u.user_id=uc.uid')
            ->where($where)
            ->count();
        $list = db('user_coupon uc')
            ->join('coupon c', 'uc.coupon_id=c.coupon_id')
            ->join('user u', 'u.user_id=uc.uid')
            ->field($field)
            ->where($where)
            ->order('uc.add_time DESC')
            ->limit(($p - 1) * $pageSize, $pageSize)
            ->select();
        if ($list) {
            foreach ($list as $k => $v) {
                $list[$k]['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
                $list[$k]['use_time'] = $v['use_time'] ? date('Y-m-d H:i:s', $v['use_time']) : 0;
                if($v['presenter_uid']){
                    $list[$k]['presenter'] = db('user')->where('user_id', $v['presenter_uid'])->value('user_nickname');
                }
            }
        }
        $data = [
            'page' => [
                'count' => $count
            ],
            'content' => $list
        ];
        return $data;
    }


    /**
     * 微信端: 获取我的优惠券列表
     * @param $sid
     * @param $uid
     * @param $p
     * @param $pageSize
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getOwnCouponListByUid($sid, $uid, $p, $pageSize)
    {
        $where = [
            'uc.sid' => $sid,
            'uc.uid' => $uid
        ];
        $field = 'c.coupon_id,c.coupon_name,c.coupon_price,c.coupon_begin,c.coupon_end,c.coupon_type,uc.status';
        $list = db('user_coupon uc')
            ->join('coupon c', 'uc.coupon_id=c.coupon_id')
            ->field($field)
            ->where($where)
            ->order('uc.status ASC,uc.add_time DESC')
            ->limit(($p - 1) * $pageSize, $pageSize)
            ->select();

        if ($list) {
            foreach ($list as $k => $v) {
                if ($v['status'] == 0) {
                    if (time() > $v['coupon_end']) {
                        //已过期
                        $list[$k]['status'] = 2;
                    }
                }
                $list[$k]['coupon_begin'] = date('Y/m/d', $v['coupon_begin']);
                $list[$k]['coupon_end'] = date('Y/m/d', $v['coupon_end']);
            }
        }
        return $list;
    }


    /**
     * 微信端: 获取可领取的优惠券列表
     * @param $sid
     * @param $uid
     * @return array
     */
    public function getOtherCouponListByUid($sid, $uid)
    {
        //查询已领取优惠券
        $own_coupon_ids = $this->getOwnCouponIds($sid, $uid);
        $cur_time = time();
        $where = [
            'sid' => $sid,
            'coupon_id' => ['not in', $own_coupon_ids],
            'surplus' => ['>', 0],
//            'coupon_begin' => ['<', $cur_time],
            'coupon_end' => ['>', $cur_time],
            'status' => 1
        ];
        $field = 'coupon_id,coupon_name,coupon_price,coupon_begin,coupon_end,receive_obj,coupon_type';
        $list = db('coupon')->field($field)->where($where)->select();
        $data = [];
        if ($list) {
            $own_status = $this->getOwnStatus($sid, $uid);
            foreach ($list as $k => $v) {
                $v['coupon_begin'] = date('Y.m.d', $v['coupon_begin']);
                $v['coupon_end'] = date('Y.m.d', $v['coupon_end']);
                $receive_obj = explode(',', $v['receive_obj']);
                if (in_array($own_status, $receive_obj)) {
                    $data[] = $v;
                }
            }
        }
        return $data;
    }


    /**
     * 微信端: 获取当前用户学员状态(1:潜在学员;2:意向学员;3:正式学员;4:顾问)
     * @param $sid
     * @param $uid
     * @return int
     */
    private function getOwnStatus($sid, $uid)
    {
        $where = [
            'ui.sid' => $sid,
            'ui.userid' => $uid
        ];
        $field = 'ui.students_id,ui.counselor_status,s.formal_status';
        $info = db('user_integral ui')
            ->join('students s', 's.uid=ui.userid', 'LEFT')
            ->field($field)
            ->where($where)
            ->find();
        if ($info['counselor_status'] == 1) {
            $status = 4; //顾问
        } elseif (!$info['students_id']) {
            $status = 1; //潜在学员
        } else {
            $status = $info['formal_status'] == 0 ? 2 : 3; //2为意向学员;3为正式学员
        }
        return $status;
    }

    /**
     * 微信端: 获取自身优惠券ID数组
     * @param $sid
     * @param $uid
     * @return array
     */
    private function getOwnCouponIds($sid, $uid)
    {
        $own_list = db('user_coupon')->field('coupon_id')->where(['sid' => $sid, 'uid' => $uid])->select();
        $own_coupon_ids = []; //保存自身领取过的优惠券ID
        if ($own_list) {
            foreach ($own_list as $k => $v) {
                $own_coupon_ids[$k] = $v['coupon_id'];
            }
        }
        return $own_coupon_ids;
    }

    /**
     * 微信端: 用户领取优惠券
     * @param $sid
     * @param $uid
     * @param $coupon_id
     * @return array
     */
    public function userReceiveCoupon($sid, $uid, $coupon_id)
    {
        $where = [
            'sid' => $sid,
            'coupon_id' => $coupon_id,
            'surplus' => ['>', 0],
//            'coupon_begin' => ['<', time()],
            'coupon_end' => ['>', time()],
            'status' => 1
        ];
        $coupon = db('coupon')->where($where)->find();
        if (!$coupon) {
            return ['status' => 0, 'msg' => '该优惠券无法领取'];
        }

        //专属券，判断领取资格
        if ($coupon['receive_obj'] != 0) {
            $own_status = $this->getOwnStatus($sid, $uid);
            $receive_obj = explode(',', $coupon['receive_obj']);
            if (!in_array($own_status, $receive_obj)) {
                return ['status' => 0, 'msg' => '对不起，您无权限领取'];
            }
        }

        //判断是否领取过
        $info = db('user_coupon')->where(['uid' => $uid, 'coupon_id' => $coupon_id])->find();
        if ($info) {
            return ['status' => 0, 'msg' => '您已经领取过了'];
        }

        Db::startTrans();
        try {
            $insert_data = [
                'uid' => $uid,
                'sid' => $sid,
                'coupon_id' => $coupon_id,
                'add_time' => time(),
                'is_admin_appoint' => 0,
                'status' => 0
            ];
            db('user_coupon')->insert($insert_data);
            //减少优惠券发放数量
            db('coupon')->where(['coupon_id' => $coupon_id])->setDec('surplus', 1);
            //增加优惠券领取数量
            db('coupon')->where(['coupon_id' => $coupon_id])->setInc('receive', 1);

            //增加领取优惠券的动态
//            $student_id = db('students')->where(['uid' => $uid, 'sid' => $sid])->value('id');
//            $dynamic_data = [
//                'studentsid' => $student_id,
//                'sid' => $sid,
//                'type' => 5,
//                'description' => '领取了《'.$coupon['coupon_name'].'》优惠券',
//                'add_time' => time()
//            ];
//            \think\Hook::listen('students_dynamic', $dynamic_data, '', true);
            $trackService = new TrackService();
            $track_msg = '领取了《' . $coupon['coupon_name'] . '》优惠券';
            $trackService->writeTrackSmall($track_msg, $sid, $uid);

            Db::commit();
            return ['status' => 1, 'msg' => '领取成功'];
        } catch (\Exception $e) {
            Db::rollback();
            return ['status' => 0, 'msg' => '领取失败'];
        }
    }

    /**
     * 微信端: 获取课程可使用的优惠券
     * @param $sid
     * @param $uid
     * @param $course_id
     * @return array
     */
    public function getCourseCouponListByUid($sid, $uid, $course_id)
    {
        $where = [
            'uc.sid' => $sid,
            'uc.uid' => $uid,
            'uc.status' => 0,
            'c.coupon_begin' => ['<', time()],
            'c.coupon_end' => ['>', time()]
        ];
        $field = 'c.coupon_id,c.coupon_name,c.coupon_price,c.coupon_begin,c.coupon_end,c.coupon_type,c.receive_classid';
        $list = db('user_coupon uc')
            ->join('coupon c', 'uc.coupon_id=c.coupon_id')
            ->field($field)
            ->where($where)
            ->order('c.coupon_price DESC')
            ->select();
        $course_class = db('course_class')->where(['courseid' => $course_id])->select();
//        if(empty($course_class)){
//            return false;
//        }
        $class_ids = [];
        foreach ($course_class as $key => $val) {
            $class_ids[$key] = $val['classid'];
        }

        $data = [];
        if ($list) {
            foreach ($list as $k => $v) {
                $v['coupon_begin'] = date('Y.m.d', $v['coupon_begin']);
                $v['coupon_end'] = date('Y.m.d', $v['coupon_end']);
                if ($v['coupon_type'] == 2) {
                    //专属券
                    //限制使用的班级ID
                    $receive_classid = explode(',', $v['receive_classid']);
                    //求交集
                    if ($class_ids && $receive_classid) {
                        if (array_intersect($class_ids, $receive_classid)) {
                            $data[] = $v;
                        }
                    }
                } else {
                    //通用券
                    $data[] = $v;
                }
            }
        }
        return $data;
    }

    public function getCounselorCouponList($sid, $uid, $p, $pageSize)
    {
        $is_counselor = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->value('counselor_status');
        if(!$is_counselor){
            return ['status' => 0, 'msg' => '非法请求'];
        }

        $field = 'coupon_id,coupon_name,coupon_price,coupon_begin,coupon_end,coupon_type,sum,surplus';
        $where = [
            'sid' => $sid,
            'coupon_end' => ['>', time()],
            'surplus' => ['>', 0],
            'receive_obj' => ['like', '%4%'], //4代表顾问
            'status' => 1
        ];
        $list = db('coupon')
                ->field($field)
                ->where($where)
                ->limit(($p - 1) * $pageSize, $pageSize)
                ->order('coupon_begin ASC')
                ->select();
        if($list){
            foreach($list as $k => $v){
                $list[$k]['coupon_begin'] = date('Y-m-d H:i:s', $v['coupon_begin']);
                $list[$k]['coupon_end'] = date('Y-m-d H:i:s', $v['coupon_end']);
            }
        }
        return $list;
    }
}